package com.hmdp.utils;
import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * 作者：24岁没牵过女人的手
 * 日期：2023/3/10 14:19
 * 文件描述：
 */
@Slf4j
public class SimpleRedisLock implements ILock{
    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true)+"-";

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        ClassPathResource classPathResource = new ClassPathResource("unlock.lua");
        UNLOCK_SCRIPT.setLocation(classPathResource);
        UNLOCK_SCRIPT.setResultType(Long.class);
    }



    /**
     * 需要自己传入的参数
     */
    private StringRedisTemplate stringRedisTemplate;
    private String lockName;

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String lockName) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.lockName = lockName;
    }

    /**
     * 获取🔒
     * @param exSecond
     * @return
     */
    @Override
    public boolean tryLock(long exSecond) {
        String threadId =ID_PREFIX + Thread.currentThread().getId();
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + lockName, threadId, exSecond, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }


    /**
     * 使用lua
     * 脚本释放🔒，保证原子性
     */
    @Override
    public void unLock() {
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX+lockName),
                ID_PREFIX + Thread.currentThread().getId()
                );
    }


    /**
     *  释放🔒
     */
//    @Override
//    public void unLock() {
//        // 获取线程标识
//        String threadId =ID_PREFIX + Thread.currentThread().getId();
//        // 获取🔒里面的标识（value值）
//        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + lockName);
//        if (threadId.equals(id)){
//            stringRedisTemplate.delete(KEY_PREFIX+lockName);
//        }
//    }

    /**
     * UUID在同一个服务是一样的，但是可以防止不同服务器的线程ID重复
     */
    public void getUUID(){
        System.out.println(ID_PREFIX);
    }
}
